//
//  DPXXVc.swift
//  Pods
//
//  Created by eme on 2017/3/28.
//
//

import UIKit
import UtilCore
import RickonCore
import CommonCore
import URLNavigator
import Kingfisher
import BrandonCore

class DPXX_Vc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    @IBOutlet weak var customTableView: UITableView!
    
    /*----------------------------   自定义属性区域    ----------------------------*/
    var titleArr = [String]()
    
    var qiniuVm:Qiniu_Vm?

    var shopVm:shopMessageVm?
    
    var spid = ""
    
    var messageModel:ShopMseeageModel?{
        didSet{
            self.customTableView.reloadData()
        }
    }
    
//    var shopVm:shopMessageVm?
    
    var headerUrl:String = ""

    var smvm:changeStoreMessageVm?                   ///修改店铺信息vm

    var LoginUserVm:GetLoginUserVm?
    
    /****************************Storyboard 绑定方法区域****************************/
    
    
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = true
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        
        if let user = AppData.loginedUser{
            self.spid = user.thrid
        }
        self.shopVm?.getShopMessage.onNext(self.spid)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setupTableView()
    }
    
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        //-----------------------------------------
        //上传图片
        
        self.qiniuVm = Qiniu_Vm()
        self.qiniuVm?.uploadImageSuccess.subscribe(onNext:{[unowned self] splicenseurl in
            
            self.smvm?.changeMessage.onNext(JSONHelper.parseToJson(["userface":splicenseurl.ImgUrl(),"spid":self.messageModel?.spid] as AnyObject) as String)
            
            self.headerUrl = splicenseurl.ImgUrl()
            
            }).addDisposableTo(disposeBag)
        
        self.qiniuVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)   ////!!!!!可能没有加载动画
        
        self.qiniuVm?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        
        //-----------------------------------------------------------
        //获取店铺信息
        self.shopVm = shopMessageVm()
        
        self.shopVm?.backMessage.subscribe(onNext:{ result in
            
            self.messageModel = result
            
            }).addDisposableTo(disposeBag)
        
        self.shopVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.shopVm?.error.asObserver().bindTo(self.view.rx_error).addDisposableTo(disposeBag)

        
        //----------------
        //上传成功并且修改店铺信息成功后获取登录对象
        
        self.smvm = changeStoreMessageVm()
        
        self.smvm?.backMessage.asObserver().subscribe(onNext:{ data in
            
            self.LoginUserVm?.getLoginUser.onNext()
            
            }).addDisposableTo(disposeBag)
        
        self.smvm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)

        
        self.LoginUserVm = GetLoginUserVm()
        
        self.LoginUserVm?.backData.asObserver().subscribe(onNext:{ _ in
            
            self.customTableView.reloadData()
            
            }).addDisposableTo(disposeBag)
    }
    func setupTableView(){
        self.customTableView.showsVerticalScrollIndicator = false
        customTableView.delegate = self
        customTableView.dataSource = self
    }
}
extension DPXX_Vc:UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        titleArr = ["","商户ID","简称","联系电话","联系人姓名","","所在省市区","详细地址","代理联系人","代理联系电话"]
        
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! DPXX_Style1_TableViewCell
            if let user = AppData.loginedUser{
                cell.header_ImageView.kf.setImage(with:URL(string: user.userface),placeholder: UIImage.init(named: "Mine_default_Image", in: SansaCore.bundle, compatibleWith: nil), options:[.transition(ImageTransition.fade(1.2))])
//                setUrlImage(user.userface, placeholderImage: "Mine_default_Image")
            }
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell3") as! DPXX_Style3_TableViewCell
            cell.titleLabel.text = titleArr[indexPath.row]
            if let model = messageModel{
                switch indexPath.row {
                case 1:
                    cell.MessageLabel.text = model.spid
                    cell.rightIcon.isHidden = true
                    cell.labelWithRight.constant = 0
                case 2:
                    cell.MessageLabel.text = model.spname
                    cell.rightIcon.isHidden = false
                case 3:
                    if model.spmobile != ""{
                        let startindex = model.spmobile.index(model.spmobile.startIndex, offsetBy: 3)
                        let endIndex = model.spmobile.index(model.spmobile.startIndex, offsetBy: 7)
                        cell.MessageLabel.text = model.spmobile.substring(to: startindex) + "****" + model.spmobile.substring(from:endIndex)
                    }
                    cell.rightIcon.isHidden = false
                default:
                    break
                }
            }
            
            return cell
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return 75
        default:
            return 45
        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            if let model = messageModel{
                switch indexPath.row {
                case 0:
                    selectIcon()
                case 1:
                    break
                case 2:
                    _ = "changedpmessage".openURL(["title":"修改简称","spname":model.spname])
                case 3:
                    _ = "changephone".openURL(["changeMessage":"修改绑定手机","phone":model.spmobile])
                default:
                    break
            }
        }
            
    }
    //-----------------------------------
    ///改变头像
    func selectIcon()
    {
        let userIconAlert = UIAlertController(title: "请选择操作", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
        
        let chooseFromPhotoAlbum = UIAlertAction.init(title: "从相册选择", style: UIAlertActionStyle.default, handler: { UIAlertAction in
            self.ChooseFromPhotoAlbum()
        })
        
        let chooseFromCamera = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default,handler:{ UIAlertAction in
            self.ChooseFromCamera()
        })
        
        let canelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler: nil)
        
        userIconAlert.addAction(canelAction)
        userIconAlert.addAction(chooseFromCamera)
        userIconAlert.addAction(chooseFromPhotoAlbum)
        
        self.present(userIconAlert, animated: true, completion: nil)
        
    }
    
    //MARK:-
    //MARK:从相册选取图片
    func ChooseFromPhotoAlbum() -> Void{
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //允许编辑
        imagePicker.allowsEditing = true
        //设置图片源
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        //模态弹出IamgePickerView
        self.present(imagePicker, animated: true, completion: nil)
    }
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    //MARK:-
    //MARK:拍照
    func ChooseFromCamera() -> Void{
        let imagePicker = UIImagePickerController()
        //设置代理
        imagePicker.delegate = self
        //允许编辑
        imagePicker.allowsEditing=true
        //设置图片源
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        //模态弹出IamgePickerView
        self.present(imagePicker, animated: true, completion: nil)
    }
    //编辑完成获取完成后的图片
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //获得编辑后的图片
        if let image = (info as NSDictionary).object(forKey: UIImagePickerControllerEditedImage) as? UIImage  {
            self.qiniuVm?.uploadImageSubject.onNext(image)
        }
        picker.dismiss(animated: true, completion: nil)
    }
}
